$(document).ready(function($, dt) {

    var idPage = $('.pagedatagrid').attr('data-id'), tabDataGrid = $('.datagrid-nav-tabs li.active a').attr('href');

    TabActive = tabDataGrid.substr(1);
    $.easyconfirm.locales = {
        title: 'Sistema pergunta',
        text: 'Deseja apagar esse registro ?',
        button: ['Cancelar', 'Confirmar'],
        closeText: 'close'


    };
    var gridW = $('.pagedatagrid').width();
    cssGrid(gridW);
    $(window).on('resize', function() {
        var gridW = $('.pagedatagrid').width();
        cssGrid(gridW);
    });

    function cssGrid(width) {
        var w = (width * 0.965);

        $('.grid-container-grids').css({
            width: (w)
        });
    }
    //    $('.grid-container-grids').mCustomScrollbar({
    //           autoHideScrollbar:true,
    //           theme:"light-thin"
    //       });

    $.fn.initializeDataGrid = function() {


        $('a.edit-action,a.add-action,a.delete-action,[role="ajax-form-render"]').datagridform({
            dialogConfirmText: 'Deseja apagar esse registro ?',
            dialogConfirmTitle: 'Sistema pergunta',
            urlFile: '/administrativo/fileconnect',
            widthBoxFile: '80%',
            heightBoxFile: 500,
            callbackCompleteForm: function(element) {
                $('select[name="estados"]').on('change', function() {

                    var ivalue = $(this).val(), obj = this;

                    if (ivalue.length > 0) {

                        $.ajax({
                            url: url_site + '/administrativo/getCidadesByEstado/' + ivalue,
                            dataType: 'json',
                            beforeSend: function() {
                                $('.cidades-container').html('<div class="grid-loading"></div>');
                                $('.cidades-container .grid-loading').show();
                            },
                            success: function(data) {
                                if (data.error == false) {
                                    $('.cidades-container').html(form_dropdown('cidade', data.options, '', 'class="form-control"'));
                                }
                            }

                        });


                    }


                });
                
                ///
                
                
                $('select[name="categorias"]').on('change', function() {

                    var ivalue = $(this).val(), obj = this;

                    if (ivalue.length > 0) {

                        $.ajax({
                            url: url_site + '/administrativo/getTipoAtivosByCategorie/' + ivalue,
                            dataType: 'json',
                            beforeSend: function() {
                                $('.ativos-container').html('<div class="grid-loading"></div>');
                                $('.ativos-container .grid-loading').show();
                            },
                            success: function(data) {
                                if (data.error == false) {
                                    $('.ativos-container').html(form_dropdown('tipo_ativo_id', data.options, '', 'class="form-control"'));
                                }
                            }

                        });


                    }


                });

            }

        });
        // $('a.delete-action').easyconfirm();
        $('a.action-start-timer-activity').on('click', function(e) {
            var attribute = $(this).attr('href'),
                    ArrayHref = attribute.split('#start:'),
                    uid = ArrayHref['1'];
            e.preventDefault();
            $(this).addClass('active');
            $('#timer-' + uid).remove();
            $(this).before('<span id="timer-' + uid + '" class="timmer-play"></span>');
            $('#timer-' + uid).countup();
        });
        // iniciando contador de atividades

        if (typeof $.fn.jCountHours == 'function') {
            $('.play-actions').jCountHours({
                ajaxUrl: url_site + 'administrator/status_atividade',
                autoSave: true
            });
        }
        if (typeof $.fn.previewMessages == 'function') {
            $('a.action-preview-list-activity').previewMessages({
                url: url_site + 'administrator/load_logs_atividades'
            });
        }

    }



    $('table.datagrid  tbody').find('tr').each(function() {
        var uid = $(this).find('td').eq(0).attr('uid');
        $(this).attr('row-id', uid);

    });
    $('table.datagrid  tbody tr').bind('click', function(e) {
        $('#activities');
    });


    datagrid.settings({
        url: grid_url
    }).initialize();

    $.fn.initializeDataGrid();


    ///localStorage

    $('.pagedatagrid').find('.section-t,.tab-pane').each(function() {


        var pat = $.Storage.loadItem(idPage + '-tab-active'),
                is_active = new RegExp(pat),
                myClass = $(this).attr('class');


        if (is_active.exec(myClass)) {
            $(this).addClass('active');

        }


    });

    var dataGridStorage = $.Storage.loadItem('tabsDataGrid') || {};


    if (dataGridStorage[idPage] !== undefined) {
        $('a[href="#' + dataGridStorage[idPage] + '"]').trigger('click');
    }

    $('.nav.nav-tabs a').on('click', function() {
        var idSection = $(this).attr('href');

        // $.Storage.deleteItem(tab);
        dataGridStorage[idPage] = idSection.substr(1);

        TabActive = idSection.substr(1);
        $.Storage.saveItem('tabsDataGrid', dataGridStorage);

    });

});


/*
 *pluginName:Datagrid
 *author:Carlos O Carvalho
 *description:
 */

void function(grid, $, document) {

    var about = {
        version: '1.0',
        _constructor: 'Datagrid',
        name: 'datagrid',
        author: 'Carlos O Carvalho'
    }, idActive = 0;


    grid._defaults = {
        'url': '',
        callback: function() {
        },
        data: {
            'current_page': 1,
            'grid_post': '',
            'grid_field': ''

        }
    };
    grid.initialize = initializeDataGrid;
    function initializeDataGrid() {
        $('button[name="grid_search"], .display-links a ,button[name="grid_reset"] , input.paginateInput').on('click keyup', function(e) {
            e.preventDefault();
            var type = $(this).attr('data-dir'),
                    idTable = $(this).attr('data-id'),
                    post = $('input[name="grid_post_' + idTable + '"]').val(),
                    field = $('select[name="grid_field_dropdown_' + idTable + '"]').val(),
                    setting = {
                        'grid_post': post,
                        'grid_field': field
                    };
            idActive = idTable;

            //remove fields
            delete grid._defaults.fields;
            if (e.type == "keyup" && e.which == 13) {
                grid.enter();
            }
            if (e.type == 'click') {
                if (type == 'search') {
                    grid.settings({
                        data: setting
                    }).run();
                }
                if (type == 'next') {
                    grid.settings({
                        data: setting
                    }).next();
                }
                if (type == 'prev') {
                    grid.settings({
                        data: setting
                    }).prev();
                }
                if (type == 'reset') {
                    grid.settings({
                        data: {}
                    }).refresh();
                }


            }


        });

    }
    grid.settings = settingsDataGrid;
    function settingsDataGrid(options) {
        var defaults = grid._defaults;

        grid._defaults = $.extend({}, defaults, options);
        return this;
    }
    grid._load = loadDataGrid;
    function loadDataGrid() {
        var url = grid._defaults.url + '/' + idActive;
        return $.ajax({
            url: url,
            data: grid._defaults.data,
            beforeSend: grid.loading.show,
            type: 'post',
            dataType: 'json'
        });


    }
    grid.enabledGrid = enabled;
    grid.display = false;
    grid._lastPage = 1;
    grid.next = nextDataGrid;
    function nextDataGrid() {
        var page = Math.ceil(parseInt(grid._page(), 10) + 1);
        if (page > grid._getLinks()) {
            page = grid._getLinks();
        }
        if (page != grid._page()) {
            grid._defaults.data.current_page = page;
            grid.run();
        }

    }
    grid.prev = prevDataGrid;
    function prevDataGrid() {
        var page = Math.ceil(parseInt(grid._page(), 10) - 1);
        if (page < 1) {
            page = 1;
        }
        if (page != grid._page() || page != grid._lastPage) {
            grid._defaults.data.current_page = page;
            grid.run();
        }
    }
    grid.refresh = refreshDataGrid;
    function refreshDataGrid() {
        grid._defaults.data = {};
        grid.run();
    }

    grid.enter = enterDataGrid;
    function enterDataGrid() {
        var page = grid._page();
        if (page < 1) {
            page = 1;
        }
        if (page > grid._getLinks()) {
            page = grid._getLinks();
        }
        if (page != grid._lastPage || page != grid._lastPage) {
            grid._defaults.data.current_page = page;
            grid.run();
        }

    }

    grid._page = getCurrentPageDataGrid;
    function getCurrentPageDataGrid() {
        return $('input[name="grid_paginate_' + idActive + '"]').val();
    }
    grid._getLinks = getTotalLinksDataGrid;
    function getTotalLinksDataGrid() {
        var links = $('.' + idActive + '').text();
        return parseInt(links, 10);
    }

    grid.setPage = setPageDataGrid;
    function setPageDataGrid(str) {
        // as_total , as_pages, current_page 

        if (grid.display == true) {
            $('.' + idActive).html(str.as_pages);
            $('.displayTotalResults_' + idActive).html(str.as_total);
            $('input[name="grid_paginate_' + idActive + '"]').val(str.current_page);

            grid._lastPage = parseInt(str.current_page, 10);
            $('input[name="grid_post_' + idActive + '"]').val(str.search);
            $('input[name="grid_field_' + idActive + '"]').val(str.field_search);

        }

    }

    grid._complete = completeDataGrid;
    function completeDataGrid() {
        grid.loading.hide();
        $.fn.initializeDataGrid();
    }


    grid.run = runDataGrid;
    function runDataGrid() {
        if (grid._defaults.url != '') {
            var load = grid._load();
            load.then(grid.html).done(grid._complete);
        }

    }

    function enabled(boll) {
        grid.display = boll == true ? true : false;
    }
    grid.html = htmlDataGrid;
    function htmlDataGrid(data) {

        var tbody = '', gbody = '', idata = data.list, ilist = data.list;

        if (data.as_total == 0) {
            $('table#datagrid-container-' + idActive + ' tbody').html('');
            $('#grid-container-div-' + idActive + '').html('');
        }
        if (ilist.length == 0) {
            return;
        } else {

            if (idata.length > 0) {
                grid.enabledGrid(true);
                for (var i in idata) {
                    if (typeof idata[i] == 'object') {
                        tbody += '<tr>';
                        gbody += '<div class="grid-row">';
                        for (var j in idata[i]) {
                            var column = idata[i][j];
                            if (typeof column == 'string') {
                                tbody += '<td>' + column + '</td>';
                                gbody += '<div class="grid-column grid-item-' + (parseInt(j, 10) + 1) + '">' + column + '</div>';
                            }
                            //add actions
                            if (typeof column == 'object') {
                                tbody += '<td style="text-align:right;" class="table-actions">';
                                gbody += '<div class="grid-box-actions">';
                                for (var l in column) {
                                    var $action = column[l],
                                            action;
                                    if ($action.replace == true) {
                                        action = $action.link;
                                    } else {
                                        action = '<a class="grid-actions action-'
                                                + $action.icon + '-" data-rel="tooltip" data-original-title="'
                                                + $action.data + '" href="' + $action.link + '"><i class="'
                                                + $action.icon + '"></i><span>' + $action.data + '</span></a>';
                                    }

                                    tbody += action;
                                    gbody += action;
                                }
                                gbody += '</div>';
                                tbody += '</td>';

                            }
                            //
                        }
                        tbody += '</tr>';
                        //end row
                        gbody += '<div class="grid-clear"></div>';
                        gbody += '</div>';
                    }

                }
                var cont = $('table#datagrid-container-' + idActive).find('tbody').size();
                if (cont == 0) {
                    $('table#datagrid-container-' + idActive + '').append('<tbody>' + tbody + '</tbody>');
                } else {
                    $('table#datagrid-container-' + idActive + ' tbody').html(tbody);

                }


                $('#grid-container-div-' + idActive + '').html(gbody);

                //atualizando display result
                grid.setPage(data);
            }
        }
    }
    grid.loading =
            loadBox = {
                show: function() {
                    $('.grid-loading').show().css({
                        'display': 'inline'
                    });
                },
                hide: function() {
                    $('.grid-loading').hide();
                }
            };
    grid._about = about;

}(window.datagrid = {}, jQuery, document);




